package cn.sms.user.controller;

import cn.sms.basic.exception.BusinessException;
import cn.sms.basic.util.AjaxResult;
import cn.sms.basic.util.PageList;
import cn.sms.user.domain.User;
import cn.sms.user.dto.UserDto;
import cn.sms.user.query.UserQuery;
import cn.sms.user.service.IUserService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
@Api(tags = "用户接口",description = "用户接口描述")
public class UserController {
    @Autowired
    private IUserService iUserService;

    @PostMapping("/phone/register")
    public AjaxResult goToRegister(@RequestBody UserDto dto){
        try {
            iUserService.goToRegister(dto);
            return AjaxResult.me();
        } catch (BusinessException e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙，请稍后重试");
        }
    }

    @GetMapping("/{id}")
    public User queryById(@PathVariable("id") Long id){
        return iUserService.queryById(id);
    }

    @GetMapping
    public List<User> queryAll(){
        return iUserService.queryAll();
    }

    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable("id") Long id){
        try {
            iUserService.remove(id);
            return AjaxResult.me();
        } catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("删除失败");
        }

    }

    @PutMapping
    public AjaxResult save(@RequestBody User user){
        try {
            if (user.getId()==null){
                iUserService.add(user);
            }else {
                iUserService.update(user);
            }
            return AjaxResult.me();
        } catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("操作失败");
        }
    }

    @PostMapping("/list")
    public PageList<User> queryPage(@RequestBody UserQuery query){
        return iUserService.queryPage(query);
    }

    @PatchMapping
    public AjaxResult batchRemoveUser(@RequestBody List<Long> ids){
        try {
            iUserService.batchRemove(ids);
            return AjaxResult.me();
        } catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("删除失败");
        }
    }

}
